package com.taobao.itest.casegen.domain;

import com.taobao.itest.casegen.service.InjectService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * User: cangfeng.mxf
 * Date: 12-9-24
 * Time: 下午4:25
 * To change this template use File | Settings | File Templates.
 */
@Component
public class RuleHouse {
    private ConcurrentHashMap<Long, ArrayList<Rule>> rules;
    private Lock lock = new ReentrantLock();
    @Resource
    protected InjectService injectService;

    @PostConstruct
    public void init(){
        rules = new ConcurrentHashMap<Long, ArrayList<Rule>>();
    }

    public List<Rule> getClientRuleList(long clientPort){
        return Collections.unmodifiableList(rules.get(clientPort));
    }

    public boolean addRuleToHouse(Rule rule){
        if(null == rules.get(rule.getClientPort())){
            boolean isLocked = lock.tryLock();

            if(isLocked){
                try{
                    ArrayList<Rule> newRuleList = new ArrayList<Rule>();
                    newRuleList.add(rule);
                    rules.putIfAbsent(rule.getClientPort(), newRuleList);
                }finally{
                    lock.unlock();
                }
                //采用asm方式注入代码
                injectService.inject(rule);
                return true;
            }
            return false;
        }else{
            ArrayList<Rule> oldRuleList = rules.get(rule.getClientPort());
            oldRuleList.add(rule);
            return true;
        }
        //return false;
    }
}
